<?php
namespace Models;

class Article extends Base {
    const ACTIVE = 1;
    const DELETED = -1;
    const HIDDEN = 0;

    const GROUP_BLOG = 0;
    const GROUP_SYSTEM = -1;

    /**
     * @var integer
     */
    protected $id;

    /**
     * @var integer
     */
    protected $author_id;

    /**
     * @var integer
     */
    protected $status_id;

    /**
     * @var integer
     */
    protected $group_id;

    /**
     * @var User
     */
    protected $author;

    /**
     * @var ArticleContent
     */
    protected $articleContent;

    /**
     * @var Attachment
     */
    protected $banner;

    protected $album_id;

    /**
     * @var Album
     */
    protected $album;

    /**
     *
     * @param array $data
     */
    public function __construct(array $data = array()) {
        parent::__construct($data);
        $this->articleContent = new ArticleContent($data);
    }

    /**
     * @return array
     */
    public function toArray() {
        return array_merge(parent::toArray(), array(
            'id' => $this->id,
            'author_id' => $this->author_id,
            'status_id' => $this->status_id,
            'group_id' => $this->group_id,
            'author' => $this->author,
            'album_id' => empty($this->album_id) ? NULL : $this->album_id
        ), $this->getContent()->toArray());
    }

    /**
     * @return ArticleContent
     */
    public function getContent() {
        return $this->articleContent;
    }

    /**
     * @return User
     */
    public function getAuthor() {
        return $this->author;
    }

    public function getAuthorId() {
        return $this->author_id;
    }

    public function getId() {
        return $this->id;
    }

    public function getStatusId() {
        return $this->status_id;
    }

    public function getGroupId() {
        return $this->group_id;
    }

    public function isAuthor(User $user) {
        return ($user->getId() == $this->author_id);
    }

    /**
     * @param integer $operation
     * @param User $user
     * @return boolean
     */
    public function cando($operation, User $user = null) {
        switch ($operation) {
            case self::OP_DELETE:
            case self::OP_WRITE:
                return $user && ($user->isAdmin() || $this->isAuthor($user));
            case self::OP_READ:
                return true;
            default:
                return false;
        }
    }

    /**
     * @return Attachment
     */
    public function getBanner() {
        return $this->banner;
    }

    public function haveBanner() {
        return !!$this->banner;
    }

    public function haveAlbum() {
        return $this->album_id > 0;
    }

    public function getAlbumId() {
        return $this->album_id;
    }

    /**
     * @return Album
     */
    public function getAlbum() {
        return $this->album;
    }
}
